from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
from django.urls import reverse

from ..models import Menu, Page


register = template.Library()


@register.simple_tag
def get_menu_items(menu_name):
    try:
        menu = Menu.objects.get(name=menu_name)
        items = menu.items.all()
        new_items = []

        # filter & verify published pages & links.
        for item in items:
            if item.item_type == item.TYPE.PAGE:
                if item.page.status == Page.STATUS.PUBLISHED:
                    new_items.append(item)
            else:
                new_items.append(item)

        return new_items
    except Menu.DoesNotExist:
        pass
    return []


@register.inclusion_tag('tags/_menu_base.html')
def render_menu(menu_name):
    try:
        menu = Menu.objects.get(name=menu_name)
        items = menu.items.all()
        new_items = []

        # filter & verify published pages & links.
        for item in items:
            if item.item_type == item.TYPE.PAGE:
                if item.page.status == Page.STATUS.PUBLISHED:
                    new_items.append(item)
            else:
                new_items.append(item)

        return {'menu_items': new_items}
    except Menu.DoesNotExist:
        pass
    return None


@register.inclusion_tag('tags/_menu_item.html')
def render_menu_item(item, before=None, after=None, link_class=None):
    url = item.url if item.item_type == item.TYPE.LINK else reverse(
        'page', kwargs={'slug': item.page.slug})

    # Passing link classes
    if link_class is not None:
        if item.css_class is not None:
            item.css_class = '%s %s' % (link_class, item.css_class)
        else:
            item.css_class = link_class

    return {
        'item': item,
        'url': url,
        'before': before,
        'after': after,
    }
